function basePath(){
    var curWwwPath = window.document.location.href;
    var pathName =  window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0,pos);
    var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return (localhostPath + projectName);
}

loading();

var page_now = -1;

$(function () {
    $(".selectpicker").selectpicker({
        noneSelectedText: '请选择',
        style: 'btn-default'
    });

    Direction();


    getAllGroup(1);

    $('[data-toggle="tooltip"]').tooltip();
});


function getAllGroup(pageNum) {
    page_now = pageNum;
    $.ajax({
        url: basePath()+'/edu/group/get_all_group.do',
        data: {'pageNum': pageNum, 'pageSize': 10},
        dataType: 'json',
        success: function (res) {
            removeLoading();
            setPage(res.data.pageNum, res.data.pages, "getAllGroup");
            if (res.success) {

                if (res.data.list == "") {
                    $('#table').hide();
                    $('#pagination').hide();
                    $('.form-horizontal').after("<div class='alert alert-warning alert-dismissible' role='alert'>\n" +
                        "  <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>\n" +
                        "  <strong style='padding-left: 30px;'>暂时没有任何分组</strong>" +
                        "</div>");
                } else {
                    $('.alert').remove();
                    $('#table').show();
                    $('#pagination').show();
                    $('#items').empty();
                    $.each(res.data.list, function (index, item) {
                        var tr = $('#temp').clone();
                        tr.removeAttr('style');
                        tr.removeAttr('id');
                        tr.find('#id').html(item.groupId);
                        tr.find('#exams').html(item.examName);
                        tr.find('#dir').html(item.directionName);
                        var interviewHtml = "";
                        if (item.interview == "未导入") {
                            interviewHtml = "<label class='label label-warning' style='margin: 1px 8px;'>" + item.interview + "</label>";
                        } else {
                            interviewHtml = "<label class='label label-success' style='margin: 1px 8px;'>" + item.interview + "</label>";
                        }
                        tr.find('#enter').html(interviewHtml);
                        tr.find('#time').html(item.groupTime);
                        tr.find('#btn').html("<button class='btn btn-info btn-sm' onclick='download("+item.groupId+")' style='padding: 2px 15px; margin-right: 10px;' ><span " +
                            "class='glyphicon glyphicon-download' aria-hidden='true' style='padding-right: 8px;'></span>导出</button>" +
                            "<button class='btn btn-danger btn-sm' style='padding: 2px 15px;' onclick='isHaveClassOutTime(" + item.groupId + ")'><span " +
                            "class='glyphicon glyphicon-th' aria-hidden='true' style='padding-right: 8px;'></span>分班</button>"
                        );

                        $('#items').append(tr);
                    });
                }
            } else {
                bootbox.alert(res.msg);
            }
        }
    });
}

function findExam() {
    $.ajax({
        url: basePath()+'/edu/class/find_by_type.do',
        type: 'post',
        data: {"type": $('#direction').val()},
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                var ids = res.data + "";
                $.ajax({
                    url: basePath()+'/edu/group/get_exam.do',
                    type: 'post',
                    data: {'classIds': ids},
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            $(".selectpicker").selectpicker({
                                noneSelectedText: '请选择',
                                style: 'btn-default'
                            });
                            $('#exam').empty();
                            $.each(res.data, function (index, item) {
                                var op = "<option value='" + item.id + "'>" + item.name + "</option>";
                                $('#exam').append(op);
                            });
                            $('.selectpicker').selectpicker('refresh');
                        } else {
                            $('#exam').empty();
                            $(".selectpicker").selectpicker({
                                noneSelectedText: res.msg
                            });
                            $('.selectpicker').selectpicker('refresh');
                        }
                    }
                });
            }
        }
    });
}

function summaryExam() {
    var exams = $('#exam').val();
    if (exams == null) {
        bootbox.alert('请至少选择一个考试');
        return false;
    }

    exams = exams.toString();

    var direction = $('#direction').val();

    var directionName = $('#direction :selected').html();
    var examNames = $('.filter-option').html();


    bootbox.confirm({
        title: "确认汇总?",
        message: "<b>方向</b>: " + directionName + "<br/><br/>" + "<b>考试</b>: " + examNames,
        buttons: {
            cancel: {
                label: '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 取消'
            },
            confirm: {
                label: '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> 确认'
            }
        },
        callback: function (result) {
            if (result) {

                var dialog = bootbox.dialog({
                    title: '请稍候',
                    message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 汇总中...</p>'
                });

                $.ajax({
                    url: basePath()+'/edu/group/summary_and_group.do',
                    type: 'post',
                    data: {'type': direction, 'exams': exams},
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            dialog.find('.modal-title').html('完成');
                            dialog.find('.modal-body').html(res.msg);
                            dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
                            getAllGroup(page_now);
                        } else {
                            dialog.find('.modal-title').html('错误');
                            dialog.find('.modal-body').html(res.msg);
                            dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
                        }
                    }
                });
            }
        }
    });
}


function download(groupId) {

    var dialog = bootbox.dialog({
        title: '请稍候',
        message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 导出中...</p>'
    });

    var groupTime = $('#items').find("th:contains('" + groupId + "')").parent().find('#time').html();
    groupTime = groupTime.replace(/-| |:/g, '_');
    var url = basePath()+'/edu/group/output_excel.do' + "?id=" + groupId;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);        // 也可以使用POST方式，根据接口
    xhr.responseType = "blob";    // 返回类型blob
    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
        // 请求完成
        if (this.status === 200) {
            // 返回200
            var blob = this.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
            reader.onload = function (e) {
                // 转换完成，创建一个a标签用于下载
                var a = document.createElement('a');
                a.download = "汇总表-" + groupTime +'.xlsx';
                a.href = e.target.result;
                $("body").append(a);    // 修复firefox中无法触发click
                a.click();
                $(a).remove();
                dialog.find('.modal-title').html('完成');
                dialog.find('.modal-body').html("导出成功");
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");

            }
        }
    };
    // 发送ajax请求
    xhr.send();

}

function toUpload() {

    var dialog = bootbox.dialog({
        title: '请稍候',
        message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 导入中...</p>'
    });

    $('#updateForm').ajaxSubmit({
        url: basePath()+'/edu/group/upload_excel.do',
        type: 'post',
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                dialog.find('.modal-title').html('完成');
                dialog.find('.modal-body').html(res.msg);
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
                getAllGroup(page_now);
            } else {
                dialog.find('.modal-title').html('错误');
                dialog.find('.modal-body').html(res.msg);
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
            }
        },
        error: function () {
            dialog.find('.modal-title').html('失败');
            dialog.find('.modal-body').html("导入失败, 请稍后重试");
            dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
        }

    });
}

function divide(groupId) {

    var text = $('#items').find("th:contains('" + groupId + "')").parent().find('#enter label').html();

    if (text == "未导入") {
        bootbox.confirm({
            message: "<b>未导入面试成绩，确认分班吗?</b>",
            buttons: {
                confirm: {
                    label: '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> 是',
                    className: 'btn-danger'
                },
                cancel: {
                    label: '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 否',
                    className: 'btn-default'
                }
            },
            callback: function (result) {
                if (result) {
                    window.location.href = basePath()+"/edu/class/edu-class-divide.do?groupId=" + groupId;
                }
            }
        });
    }else {
        window.location.href = basePath()+"/edu/class/edu-class-divide.do?groupId=" + groupId;
    }


}

function Direction() {
    $.ajax({
        url: basePath()+"/edu/stu/get_all_direction.do",
        type: 'GET',
        success: function (res) {
            if (res.success) {
                $("#direction option").remove();
                if (res.data.length == 0) {
                    var content = "<option>暂无数据</option>";
                    $("#direction").append(content);
                } else {
                    for (var i = 0, a = res.data.length; i < a; i++) {
                        var content = "<option value='" + res.data[i].id + "'>" + res.data[i].name + "</option>";
                        $("#direction").append(content);
                    }
                }
                findExam();
            }
        }
    })
}

function isHaveClassOutTime(groupId){
    $.ajax({
        url: basePath() + "/edu/group/get_class_count.do",
        type:'GET',
        data : {
            "groupId" : groupId
        },
        dataType:'json',
        success:function (res) {
            if(res.success){
                var i = "";
                for(var d = 0; d<res.data.names.length;d++){
                    i+= res.data.names[d];
                    if(d!=res.data.names.length-1){
                        i += ",";
                    }
                }
                bootbox.confirm({
                    message: "<b>存在未注销班级，是否将其注销?</b><br/><br/> <b>班级: </b>"+i,
                    buttons: {
                        confirm: {
                            label: '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> 是',
                            className: 'btn-danger'
                        },
                        cancel: {
                            label: '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 否',
                            className: 'btn-default'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var createDate = res.data.classVo.createDate;
                            var direction = res.data.classVo.direction;
                            $.ajax({
                                url: basePath() + "/edu/group/update_class_state.do",
                                type : 'POST',
                                data : {
                                    "createDate" : createDate,
                                    "direction" : direction
                                },
                                dataType:'json',
                                success : function(res){
                                    if(res.success){
                                        divide(groupId);
                                    }else{
                                        bootbox.alert(res.msg);
                                    }
                                }
                            });
                        }
                    }
                });
            }else{
                divide(groupId);
            }
        }
    })
}